import axios from "axios";
import WebUtils from "@/utils/webUtils";

const apiUrl = "http://localhost:8081/product";

export const getCount = async ()=>{
    try {
        WebUtils.addToken();
        let response = await axios.get(`${apiUrl}/count`);
        WebUtils.isRedirect(response.data.code);
        return response.data;
    } catch (error) {
        throw error;
    }
}

export const getProductList = async (page, pageSize) => {
    try {
        WebUtils.addToken();
        let response = await axios.get(`${apiUrl}/list?page=${page}&pageSize=${pageSize}`);
        return response.data;
    } catch (error) {
        throw error;
    }
}

export const getProduct = async (productId)=>{
    try{
        WebUtils.addToken();
        let response = await axios.get(`${apiUrl}/${productId}`);
        return response.data;
    }catch (error){
        throw error;
    }
}

export const deleteProduct = async (productId) => {
    try {
        WebUtils.addToken();
        const response = await axios.delete(`${apiUrl}?id=${productId}`);
        WebUtils.isRedirect(response.data.code);
        return response.data;
    } catch (error) {
        throw error;
    }
}

export const updateProduct = async (productId, product) => {
    try {
        WebUtils.addToken();
        const response = await axios.put(`${apiUrl}?id=${productId}`, product, {
            headers: {
                'Content-Type': 'application/json',
            },
        });
        WebUtils.isRedirect(response.data.code);
        return response.data;
    } catch (error) {
        throw error;
    }
}

export const addProduct = async (product) => {
    try {
        WebUtils.addToken();
        const response = await axios.post(`${apiUrl}`, product, {
            headers: {
                'Content-Type': 'application/json',
            },
        })
        WebUtils.isRedirect(response.data.code);
        return response.data;
    } catch (error) {
        throw error;
    }
}

export const selectProductPyType = async (productType) => {
    try {
        WebUtils.addToken();
        const response = await axios.get(`${apiUrl}/selectByType?typeName=` +
            productType, {
            headers: {
                'Content-Type': 'application/json',
            },
        })
        WebUtils.isRedirect(response.data.code);
        return response.data;
    } catch (error) {
        throw error;
    }
}
